const resolve = require('path').resolve
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const { VueLoaderPlugin } = require('vue-loader')
const os = require('os')
const url = require('url')
const publicPath = ''
const glob = require('glob')
const path = require('path')

let plugins = [
  new webpack.DllReferencePlugin({
    context: __dirname,
    manifest: require('./manifest.json'),
  }),
  new VueLoaderPlugin(),
  new HtmlWebpackPlugin({
    filename: 'index.html',
    template: './index.html',
    inject: true,
    chunks: ['vendor', 'manifest']
  }),
  new CopyWebpackPlugin([{
    from: __dirname + '/src/assets/js/lib.js',
    to: __dirname + '/dist/assets/js/lib.js'
  }]),
  new UglifyJSPlugin({
    exclude: /\.min\.js$/,
    parallel: os.cpus().length,
    uglifyOptions: {
      ecma: 5,
      compress: {
        warnings: false,
        drop_console: true,
        drop_debugger: true
      }
    }
  }),
  new BundleAnalyzerPlugin(),
  new MiniCssExtractPlugin({
    filename: "[name].css",
    chunkFilename: "[name].css"
  })
]

// fix loaderUtils.parseQuery() received.
process.noDeprecation = true

module.exports = (options = {dev: false}) => {
  var webpackConfig = {
    entry: {
      vendor: './src/main',
    },
    output: {
      path: resolve(__dirname, 'dist'),
      filename: options.dev ? 'js/[name].js' : 'js/[name].js?[chunkhash]',
      chunkFilename: '[name].js?[chunkhash]',
      publicPath: options.dev ? '/assets/' : publicPath
    },
    module: {
      rules: [{
          test: /\.vue$/,
          use: ['vue-loader']
        },
        {
          test: /\.js$/,
          use: ['babel-loader'],
          exclude: /node_modules/
        },
        {
          test: /\.css$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader?minimize', 'postcss-loader']
        },
        {
          test: /\.scss$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader?minimize', 'sass-loader']
        },
        {
          test: /\.(png|jpg|jpeg|gif)(\?.+)?$/,
          use: [{
            loader: 'url-loader',
            options: {
              limit: 10000,
              name: 'images/[hash].[ext]'
            }
          }]
        },
        {
          test: /\.(eot|ttf|woff|woff2|svg|svgz)(\?.+)?$/,
          use: [{
            loader: 'url-loader',
            options: {
              limit: 10000,
              name: 'fonts/[hash].[ext]'
            }
          }]
        }
      ]
    },
    plugins: plugins,
    resolve: {
      alias: {
        '~': resolve(__dirname, 'src'),
        vue: 'vue/dist/vue.common.js',
      }
    }
  }

  webpackConfig.mode = 'production';

  return webpackConfig
}
